package com.carbon.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.common.annotation.Anonymous;
import com.carbon.common.core.domain.AjaxResult;
import com.carbon.common.utils.SecurityUtils;
import com.carbon.domain.Provider;
import com.carbon.service.ProviderService;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.carbon.utils.QiniuUtils;
import com.carbon.vo.SearchParams;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 供应商(Provider)表控制层
 *
 * @author WangFK
 * @since 2023-08-21 13:19:47
 */
@RestController
@Slf4j
@RequestMapping("/wms/provider")
public class ProviderController {
    /**
     * 服务对象
     */
    @Resource
    private ProviderService providerService;
    @Resource
    private QiniuUtils qiniuUtils;

    /**
     * 修改供应商状态
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/changeProviderStatus")
    public AjaxResult changeProviderStatus(Integer id,String status){
        Provider provider = new Provider();
        provider.setId(id);
        provider.setStatus(status);
        provider.setUpdateTime(DateUtil.date());
        provider.setUpdateBy(SecurityUtils.getUsername());
        return providerService.updateById(provider)?AjaxResult.success():AjaxResult.error();
    }
    /**
     * 分页
     * @param params
     * @return
     */
    @GetMapping("/list")
    AjaxResult list(SearchParams params){
        Page<Provider> providerPage = new Page<>(params.getPageNum(), params.getPageSize());
        LambdaUpdateWrapper<Provider> lqw = new LambdaUpdateWrapper<Provider>()
                .like(ObjectUtil.isNotEmpty(params.getSearch()), Provider::getName, params.getSearch());
         providerPage = providerService.page(providerPage, lqw);
        List<Provider> records = providerPage.getRecords();
        if (ObjectUtil.isEmpty(records)){
            return AjaxResult.success();
        }
        return AjaxResult.success()
                .put("rows",records)
                .put("total",providerPage.getTotal());
    }
    /**
     * 图片上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Anonymous
    @PostMapping("/upload")
    AjaxResult upload(@RequestBody MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        ArrayList<String> strings = new ArrayList<>();
        strings.add(".jpg");
        strings.add(".png");
        String url = "http://picture.hibox.cloud/";
        // 后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!strings.contains(substring)) {
            return AjaxResult.error("只能上传jpg/png文件，且不超过500kb");
        }
        String fileName = IdUtil.fastSimpleUUID() + substring;
        qiniuUtils.upload2Qiniu(file.getBytes(), fileName);
        return AjaxResult.success()
                .put("name", originalFilename)
                .put("file", url + fileName);
    }

    /**
     * 获取供应商列表
     * @return
     */
    @GetMapping("/getInfoList")
    public AjaxResult providerList() {
        LambdaUpdateWrapper<Provider> lqw = new LambdaUpdateWrapper<Provider>()
                .eq(Provider::getStatus, "0");
        List<Provider> list = providerService.list(lqw);
        return AjaxResult.success(list);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        return AjaxResult.success(providerService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param provider 实体对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult insert(@RequestBody Provider provider) {
        if (ObjectUtil.isEmpty(provider.getName())){
            return AjaxResult.error("供应商名为空");
        }
        if (ObjectUtil.isNotEmpty(provider.getId())){
            return update(provider);
        }
        LambdaUpdateWrapper<Provider> lqw = new LambdaUpdateWrapper<Provider>()
                .eq(Provider::getName, provider.getName())
                .eq(Provider::getStatus,"0");
        List<Provider> list = providerService.list(lqw);
        if (!list.isEmpty()){
            return AjaxResult.error("供应商："+provider.getName()+"已存在,请勿重复添加");
        }
        provider.setCreateBy(SecurityUtils.getUsername());
        provider.setCreateTime(DateUtil.date());
        return providerService.save(provider)?AjaxResult.success():AjaxResult.error();
    }

    /**
     * 修改数据
     *
     * @param provider 实体对象
     * @return 修改结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody Provider provider) {
        Provider byId = providerService.getById(provider.getId());
        if (!byId.getName().equalsIgnoreCase(provider.getName())){
            LambdaUpdateWrapper<Provider> lqw = new LambdaUpdateWrapper<Provider>()
                    .eq(Provider::getName, provider.getName())
                    .eq(Provider::getStatus,"0");
            List<Provider> list = providerService.list(lqw);
            if (!list.isEmpty()){
                return AjaxResult.error("供应商："+provider.getName()+"已存在,请勿重复添加");
            }
        }
        String logo = provider.getLogo();
        String logo1 = byId.getLogo();
        if (ObjectUtil.isNotEmpty(logo)){
            if (!logo.equalsIgnoreCase(logo1)){
                if (ObjectUtil.isNotEmpty(logo1)){
                    List<String> split = StrUtil.split(logo1, "/");
                    qiniuUtils.deleteFileFromQiniu(split.get(split.size()-1));
                }
            }
        }
        provider.setUpdateBy(SecurityUtils.getUsername());
        provider.setUpdateTime(DateUtil.date());
        return providerService.updateById(provider)?AjaxResult.success():AjaxResult.error();
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public AjaxResult delete(@PathVariable String id) {
        List<String> split = StrUtil.split(id, ",");
        List<Provider> providers = providerService.listByIds(split);
        // 删除图片
        providers.stream().filter(item->{
            if (item.getLogo()==null){
                return false;
            }
            return true;
        }).map(Provider::getLogo).forEach(item->{
            List<String> split1 = StrUtil.split(item, ",");
            qiniuUtils.deleteFileFromQiniu(split1.get(split1.size()-1));
        });
        providerService.removeByIds(split);
        return AjaxResult.success();
    }
}

